package com.settlement.system.controller;

import com.settlement.system.csv.CsvExportBuilder;
import com.settlement.system.csv.CsvExportUtil;
import com.settlement.system.common.enums.ChannelEnum;
import com.settlement.system.common.enums.ReturnStatusEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.model.entity.common.TblBalanceWatcher;
import com.settlement.system.model.entity.common.TblReceiveRefundAccount;
import com.settlement.system.model.entity.common.TblReceiveRefundShop;
import com.settlement.system.reply.ObjectDataResponse;
import com.settlement.system.service.IBaseService;
import com.settlement.system.service.ITblBalanceWatcherService;
import com.settlement.system.service.ITblReceiveRefundAccountService;
import com.settlement.system.service.ITblReceiveRefundShopService;
import com.settlement.system.service.csv.DateSpiltCsvDatas;
import com.settlement.system.common.util.common.FasUtil;
import com.alibaba.excel.context.AnalysisContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * RR-日记账-余额监控 前端控制器
 * @author Ximi
 * @since 2020-11-17
 */
@Slf4j
@Api(tags = "RR-日记账-余额监控",description = "RR-日记账-余额监控")
@RestController
@RequestMapping("/tblBalanceWatcher")
public class TblBalanceWatcherController extends ExcelController<TblBalanceWatcher> {

    @Value("${system.export-root.path}")
    private String exportRootPath;

    @Resource
    private ITblBalanceWatcherService tblBalanceWatcherService;

    @Resource
    private ITblReceiveRefundShopService tblReceiveRefundShopService;

    @Resource
    private ITblReceiveRefundAccountService tblReceiveRefundAccountService;

    @Override
    public IBaseService init() {
        return tblBalanceWatcherService;
    }

    @Override
    public Class<?> getModelClass() {
        return TblBalanceWatcher.class;
    }

    @Override
    protected void setParamsModel(Map<String, Object> model) {
        FasUtil.formatInQueryCondition(model, "ncShopNo","loginAccount");
        super.setParamsModel(model);
    }

    @Override
    protected void setFootModel(Map<String, Object> result, Map<String, Object> model) throws ServiceException {
        TblBalanceWatcher foot= tblBalanceWatcherService.getFoot(model);
        result.put("foot", foot==null? getModelClass():foot);
    }

    @Override
    public String verifyImportObject(TblBalanceWatcher detail, AnalysisContext analysisContext) {
        String errorMsg = super.verifyImportObject(detail, analysisContext);
        if(StringUtils.isNotEmpty(errorMsg)){
            return errorMsg;
        }

        Map<String,String> map = new HashMap<>(16);
        map.put(ChannelEnum.TM.getName(),ChannelEnum.TM.getNo());
        map.put(ChannelEnum.JD.getName(),ChannelEnum.JD.getNo());
        map.put(ChannelEnum.OR.getName(),ChannelEnum.OR.getNo());
        map.put(ChannelEnum.DY.getName(),ChannelEnum.DY.getNo());

        if(!map.keySet().contains(detail.getChannelName())){
            return "渠道应为其中一个："+map.keySet().toString();
        }

        detail.setChannelNo(map.get(detail.getChannelName()));

        try{
             String channelName = detail.getChannelName();
            if(channelName.equals(ChannelEnum.TM.getName()) || channelName.equals(ChannelEnum.JD.getName()) || channelName.equals(ChannelEnum.DY.getName())){
                if(StringUtils.isEmpty(detail.getShopNo())){
                    return "零售店铺编码不能为空";
                }
                TblReceiveRefundShop shop = tblReceiveRefundShopService.getByShopNo(detail.getShopNo());
                if (shop == null) {
                    return "店铺在店铺设置中不存在";
                }
                detail.setNcShopNo(shop.getNcShopNo());
                detail.setNcShopName(shop.getNcShopName());
                detail.setShopName(shop.getShopName());
            }

            if(channelName.equals(ChannelEnum.OR.getName())){
                if(StringUtils.isEmpty(detail.getLoginAccount())){
                    return "账号不能为空";
                }
                TblReceiveRefundAccount refundAccount = tblReceiveRefundAccountService.getOrByShopAccount(detail.getLoginAccount());
                if (null == refundAccount) {
                    return "账号在账号设置中不存在";
                }
            }
            detail.setDifAmount(detail.getEndAmount().subtract(detail.getAccountAmount()));
            detail.setIsStartItem("Y");
        } catch (Exception ex) {
            log.error("system error:", ex);
            return "系统异常";
        }

        return null;
    }

    @Override
    protected void saveData(List<TblBalanceWatcher> datas) throws ServiceException {
        try{
            tblBalanceWatcherService.saveData(datas);
        }catch (Exception ex){
            log.error("导入数据异常", ex);
            throw new ServiceException("导入数据异常", ex);
        }
    }

    @ApiOperation("刷新")
    @RequestMapping(value = "refresh", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse refresh(@RequestBody Map<String, Object> model, HttpServletRequest request) {
        try {
            FasUtil.formatInQueryCondition(model, "ncShopNo","loginAccount");
            tblBalanceWatcherService.refresh(model);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS);
        } catch (Exception ex) {
            log.info("更新数据异常", ex);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL);
        }
    }

    @ApiOperation("getTheOriginCount")
    @RequestMapping(value = "getTheOriginCount", method = {RequestMethod.POST})
    public ObjectDataResponse getTheOriginCount(@RequestBody Map<String, Object> model) {
        Map<String, Object> result = new HashMap<>(16);
        try {

            int count = tblBalanceWatcherService.selectOriginBillCount(model);
            result.put("originCount", count);
        } catch (Exception ex) {
            log.error("获取originCount出错", ex);
            return new ObjectDataResponse(500, "获取originCount失败，请联系管理员！");
        }
        return new ObjectDataResponse<Map>(result, 200, "获取originCount成功");
    }

    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> params = buildParam(request);
        setParamsModel(params);
        Object fileName = "RR-日记账-余额监控";
        String path = exportRootPath + System.currentTimeMillis() + "/";
        CsvExportUtil.createCsv()
                .headClass(getModelClass())
                .fileName(fileName.toString())
                .model(CsvExportBuilder.MULTI_ZIP_MODEL)
                .parentPath(path)
                .csvDatas(new DateSpiltCsvDatas(tblBalanceWatcherService, params))
                .export(request,response);
    }
}

